from google.appengine.api import urlfetch

import urllib
import urllib2
import logging
from google.appengine.ext import ndb
import webapp2
from GCM import *
import sys

API_KEY = 'AIzaSyAlUrLg7cPZcgjFdW9IwoED25kgK6y8cnQ'
URL = 'https://android.googleapis.com/gcm/send'

def sendMessageToServer(registration_ids,messageType, data=None):
    headers = {'Authorization': 'key=%s' % API_KEY}

    headers['Content-Type'] = 'application/json'

    payload = dict()
    payload['messageType'] = messageType
    payload['registration_ids'] =registration_ids
    if data:
        payload['data'] = data
    try:
        req = urllib2.Request(URL, json.dumps(payload), headers)
        response = urllib2.urlopen(req)

    except urllib2.HTTPError as err:
        logging.info(payload)
        logging.info(err.code)
    else:
        logging.info(response.read())





    #form_fields = {
    #"registration_ids":registration_ids,
    #"collapse_key": collapse_key
    #}
    #if(not(data is None)):
     #   form_fields["data"] = data



#    form_data = urllib.urlencode(form_fields)
 #   result = urlfetch.fetch(url=URL,
  #      payload=form_data,
   #     method=urlfetch.POST,
    #    headers={'Content-Type': 'application/json', 'Authorization':'key='+API_KEY})

    #return result

def sendMessageToClients(messageType, registration_ids,is_json=True,data = None):
    headers = {'Authorization': 'key=%s' % API_KEY}

    headers['Content-Type'] = 'application/json'

    payload = dict()
    payload['messageType'] = messageType
    payload['registration_ids'] =registration_ids
    if data:
        payload['data'] = data
    req = urllib2.Request(URL, json.dumps(payload), headers)
    response = urllib2.urlopen(req)
    output = response.read()
    logging.info(output)


class DeviceRegisterHandler(webapp2.RequestHandler):
    def post(self):
        user_key = ndb.Key('User',int(self.request.POST.get('userID')))
        user = user_key.get()
        user.RegID = self.request.POST.get("regID")
        user.put()



		
		
		